<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix">
        <span>
          <el-tooltip class="item" effect="dark" content="条件必须都满足才能执行对应的命令动作" placement="top-start">
            <i class="el-icon-question" />
          </el-tooltip>
          <span>{{ $t('condition') }}</span>
        </span>
        <div style="float: right">
          <el-button
            type="success"
            :disabled="!linkage.linkageTag"
            @click="insertOrUpdateLinkageConditionToDevice"
          >{{ $t('confirm') }}
          </el-button>
          <el-button type="primary" :disabled="!linkage.linkageTag" @click="addSettingCondition">{{ $t('setting') }}
          </el-button>
          <el-button type="primary" :disabled="!linkage.linkageTag" @click="addExplainCondition">{{ $t('sensor') }}
          </el-button>
          <el-button type="primary" :disabled="!linkage.linkageTag" @click="addTimerCondition">{{ $t('time') }}
          </el-button>
        </div>
      </div>
      <el-table
        :show-header="false"
        :data="conditionList"
        style="min-height: 200px"
      >
        <el-table-column>
          <template slot-scope="scope">
            <div style="display: flex;justify-content: space-between;align-items: center">
              <div v-if="scope.row.type === 'set'">
                <div class="flex">
                  <el-cascader
                    v-model="scope.row.selectedSetting"
                    style="width: 250px;margin-right: 5px"
                    :options="sensorWithSettingSelectList"
                    expand-trigger="hover"
                    @change="settingChange(scope.row)"
                  >
                    <template slot-scope="{ node, data }">
                      <span>{{ data.label }}</span>
                    </template>
                  </el-cascader>
                  <el-select
                    v-model="scope.row.logic"
                    style="width: 90px;margin-right: 5px"
                    clearable
                    filterable
                  >
                    <el-option :label="$t('greater')" value=">" />
                    <el-option :label="$t('less')" value="<" />
                    <el-option :label="$t('equal')" value="=" />
                  </el-select>
                  <div v-if="scope.row.settingType === 'fixedParam'">
                    <el-select
                      v-model="scope.row.value"
                      filterable
                      :disabled="scope.row.disabled"
                    >
                      <el-option
                        v-for="item in scope.row.paramList"
                        :key="item.value"
                        :label="item.name"
                        :value="item.value"
                      />
                    </el-select>
                  </div>
                  <div v-else-if="scope.row.settingType === 'switch'">
                    <el-switch
                      v-model="scope.row.value"
                      :disabled="scope.row.disabled"
                      :active-text="$t('open')"
                      :inactive-text="$t('close')"
                      active-value="1"
                      inactive-value="0"
                    />
                  </div>
                  <div v-else-if="scope.row.settingType === 'time'">
                    <el-time-picker
                      v-model="scope.row.value"
                      :disabled="scope.row.disabled"
                      style="width:300px"
                      value-format="HH:mm"
                      format="HH:mm"
                      :placeholder="$t('timing')"
                    />
                  </div>
                  <div v-else-if="scope.row.settingType === 'slider'">
                    <el-slider
                      v-model="scope.row.value"
                      style="width:300px"
                      :disabled="scope.row.disabled"
                    />
                  </div>
                  <div v-else>
                    <el-input
                      v-model="scope.row.value"
                      style="width:300px"
                      :disabled="scope.row.disabled"
                    />
                  </div>
                </div>
              </div>
              <div v-else-if="scope.row.type === 's'">
                <div>
                  <el-cascader
                    v-model="scope.row.selectedExplain"
                    style="width: 250px;margin-right: 5px"
                    :options="sensorWithExplainSelectList"
                    expand-trigger="hover"
                  >
                    <template slot-scope="{ node, data }">
                      <span>{{ data.label }}</span>
                    </template>
                  </el-cascader>
                  <el-select
                    v-model="scope.row.logic"
                    style="margin-right: 5px"
                    clearable
                    filterable
                  >
                    <el-option :label="$t('greater')" value=">" />
                    <el-option :label="$t('less')" value="<" />
                    <el-option :label="$t('equal')" value="=" />
                  </el-select>
                  <el-input v-model="scope.row.value" style="width: 150px" />
                </div>
              </div>
              <div v-else-if="scope.row.type === 't2'">
                <div style="margin-bottom: 10px">
                  <el-checkbox v-model="scope.row.allDay" style="margin-right: 10px">{{ $t('allDay') }}
                  </el-checkbox>
                  <el-time-picker
                    v-if="!scope.row.allDay"
                    v-model="scope.row.startDate"
                    style="margin-right: 5px"
                    value-format="HH:mm"
                    format="HH:mm"
                    :placeholder="$t('startDate')"
                  />
                  <el-time-picker
                    v-if="!scope.row.allDay"
                    v-model="scope.row.endDate"
                    value-format="HH:mm"
                    format="HH:mm"
                    :placeholder="$t('endDate')"
                  />
                </div>
                <el-checkbox
                  v-model="checkDayAll"
                  style="margin-bottom: 10px"
                  :indeterminate="isIndeterminate"
                  @change="handleCheckAllChange"
                >{{ $t('week') }}
                </el-checkbox>
                <el-checkbox-group v-model="checkDay" @change="handleCheckedDaysChange">
                  <el-checkbox
                    v-for="day in days"
                    :key="day.value"
                    :label="day.value"
                  >{{ day.label }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
              <el-button
                type="danger"
                class="el-icon-delete"
                @click="delCondition(scope.row)"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import {
  insertOrUpdateLinkageConditionToDevice,
  insertOrUpdateLinkageConditionToServer,
  listLinkageCondition
} from '@/api/iot/iotDeviceLinkageConditionApi'
import { listSensorWith } from '@/api/iot/iotDeviceSensorApi'
import { failureNotice, formatSensorType, successNotice } from '@/util/common'

export default {
  name: 'LinkageCondition',
  props: {
    linkage: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      conditionList: [],
      isIndeterminate: false,
      checkDayAll: false,
      checkDay: [],
      days: [],
      sensorWithExplainSelectList: [],
      sensorWithSettingSelectList: [],
      sensorList: []
    }
  },
  watch: {
    linkage: {
      deep: true,
      handler() {
        this.listLinkageCondition()
      }
    }
  }, created() {
    this.days = [
      {
        label: this.$t('sunday'),
        value: 7
      },
      {
        label: this.$t('monday'),
        value: 1
      },
      {
        label: this.$t('tuesday'),
        value: 2
      },
      {
        label: this.$t('wednesday'),
        value: 3
      },
      {
        label: this.$t('thursday'),
        value: 4
      },
      {
        label: this.$t('friday'),
        value: 5
      },
      {
        label: this.$t('saturday'),
        value: 6
      }
    ]
    this.listSensorWithExplain()
  }, methods: {
    formatSensorType(type) {
      return formatSensorType(this, type)
    },
    handleCheckAllChange(value) {
      if (value) {
        this.checkDay = [7, 1, 2, 3, 4, 5, 6]
        this.isIndeterminate = false
        this.checkDayAll = true
      } else {
        this.checkDay = []
        this.isIndeterminate = false
        this.checkDayAll = false
      }
    },
    handleCheckedDaysChange(value) {
      const checkedCount = value.length
      this.checkDayAll = checkedCount === 7
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < 7
    },
    listSensorWithExplain() {
      listSensorWith({
        deviceId: this.linkage.deviceId,
        withExplain: true,
        withSetting: true
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.sensorList = data
          const sensorWithExplainSelectList = []
          for (let i = 0; i < data.length; i++) {
            const sensor = data[i]
            const item = {
              value: sensor.port,
              label: this.formatSensorType(sensor.type) + this.$t('port') + ':' + sensor.port + '  ' + sensor.sensorName,
              children: []
            }
            const sensorExplainListLen = sensor.explainList.length
            for (let j = 0; j < sensorExplainListLen; j++) {
              const explain = sensor.explainList[j]
              item.children.push({
                value: explain.keyName,
                label: explain.name
              })
            }
            sensorWithExplainSelectList.push(item)
          }
          this.sensorWithExplainSelectList = sensorWithExplainSelectList

          const sensorWithSettingSelectList = []
          for (let i = 0; i < data.length; i++) {
            const sensor = data[i]
            const item = {
              value: sensor.port,
              label: this.formatSensorType(sensor.type) + this.$t('port') + ':' + sensor.port + '  ' + sensor.sensorName,
              children: []
            }
            const sensorSettingListLen = sensor.settingList.length
            for (let j = 0; j < sensorSettingListLen; j++) {
              const setting = sensor.settingList[j]
              item.children.push({
                value: setting.keyName,
                label: setting.name
              })
            }
            sensorWithSettingSelectList.push(item)
          }
          this.sensorWithSettingSelectList = sensorWithSettingSelectList
        } else {
          this.sensorList = []
          this.sensorWithExplainSelectList = []
          this.sensorWithSettingSelectList = []
        }
        this.listLinkageCondition()
      })
    },
    delCondition(item) {
      for (let i = 0; i < this.conditionList.length; i++) {
        if (item === this.conditionList[i]) {
          this.conditionList.splice(i, 1)
        }
      }
    },
    addSettingCondition() {
      this.conditionList.push({
        type: 'set'
      })
    },
    addExplainCondition() {
      this.conditionList.push({
        type: 's'
      })
    },
    addTimerCondition() {
      for (let i = 0; i < this.conditionList.length; i++) {
        if (this.conditionList[i].type === 't2') {
          failureNotice(this, '只能一个时间范围')
          return
        }
      }
      this.conditionList.push({
        type: 't2'
      })
    },
    insertOrUpdateLinkageConditionToDevice() {
      for (let i = 0, j = this.conditionList.length; i < j; i++) {
        const condition = this.conditionList[i]
        if (condition.type === 'set') {
          if (
            condition.selectedSetting == null ||
            condition.selectedSetting === ''
          ) {
            failureNotice(this, this.$('sensor'))
            return
          } else {
            condition.port = condition.selectedSetting[0]
            condition.keyName = condition.selectedSetting[1]
          }
          if (
            condition.logic == null ||
            condition.logic === ''
          ) {
            failureNotice(this, this.$t('logic'))
            return
          }
          if (
            condition.value == null ||
            condition.value === ''
          ) {
            failureNotice(this, this.$t('value'))
            return
          }
        } else if (condition.type === 's') {
          if (
            condition.selectedExplain == null ||
            condition.selectedExplain === ''
          ) {
            failureNotice(this, this.$('sensor'))
            return
          } else {
            condition.port = condition.selectedExplain[0]
            condition.keyName = condition.selectedExplain[1]
          }
          if (
            condition.logic == null ||
            condition.logic === ''
          ) {
            failureNotice(this, this.$t('logic'))
            return
          }
          if (
            condition.value == null ||
            condition.value === ''
          ) {
            failureNotice(this, this.$t('value'))
            return
          }
        } else if (condition.type === 't2') {
          if (!condition.allDay) {
            if (
              condition.startDate == null ||
              condition.startDate === ''
            ) {
              failureNotice(this, this.$t('startDate'))
              return
            }
            if (
              condition.endDate == null ||
              condition.endDate === ''
            ) {
              failureNotice(this, this.$t('endDate'))
              return
            }
            condition.allDay = 0
          } else {
            condition.allDay = 1
          }
          if (condition.startDate && condition.endDate) {
            condition.timer =
              condition.startDate + ' / ' + condition.endDate
          }
          let day = ''
          for (const index of this.checkDay) {
            day = day + index
          }
          condition.day = day
        }
      }

      if (this.linkage.type === 'device') {
        insertOrUpdateLinkageConditionToDevice({
          linkageId: this.linkage.linkageId,
          conditionList: this.conditionList
        }).then(res => {
          const { code } = res
          if (code === '200') {
            successNotice(this)
          }
          this.listLinkageCondition()
        })
      } else if (this.linkage.type === 'server') {
        insertOrUpdateLinkageConditionToServer({
          linkageId: this.linkage.linkageId,
          conditionList: this.conditionList
        }).then(res => {
          const { code } = res
          if (code === '200') {
            successNotice(this)
          }
          this.listLinkageCondition()
        })
      } else {
        failureNotice(this, this.$t('type'))
        return
      }
    },
    settingChange(item) {
      for (const sensor of this.sensorList) {
        for (const deviceSetting of sensor.settingList) {
          if (deviceSetting.keyName === item.selectedSetting[1] && deviceSetting.port === item.selectedSetting[0]) {
            for (const i in this.conditionList) {
              const target = this.conditionList[i]
              if (target.selectedSetting[1] === item.selectedSetting[1] && target.selectedSetting[0] === item.selectedSetting[0]) {
                target.settingType = deviceSetting.type
                this.conditionList.splice(i, 1, target)
                return
              }
            }
          }
        }
      }
    },
    formatCondition(condition) {
      if (condition.type === 's') {
        condition.selectedExplain = [
          condition.port,
          condition.keyName
        ]
      } else if (condition.type === 'set') {
        for (const sensor of this.sensorList) {
          for (const deviceSetting of sensor.settingList) {
            if (deviceSetting.keyName === condition.keyName && deviceSetting.port === condition.port) {
              condition.selectedSetting = [
                deviceSetting.port,
                deviceSetting.keyName
              ]
              if (deviceSetting.type === 'slider') {
                condition.value = parseInt(condition.value)
              }
              condition.paramList = deviceSetting.paramList
              condition.settingType = deviceSetting.type
            }
          }
        }
      } else if (condition.type === 't2') {
        if (condition.allDay === 0) {
          condition.allDay = false
          condition.startDate = condition.timer.split(' / ')[0]
          condition.endDate = condition.timer.split(' / ')[1]
        } else {
          condition.allDay = true
        }
        const day = condition.day.split('')
        const dayList = []
        for (const i of day) {
          dayList.push(parseInt(i))
        }
        if (day.length > 0) {
          if (dayList.length === 7) {
            this.isIndeterminate = false
            this.checkDayAll = true
          } else {
            this.isIndeterminate = true
            this.checkDayAll = false
          }
        } else {
          this.isIndeterminate = false
          this.checkDayAll = false
        }
        this.checkDay = dayList
      }
      return condition
    },
    listLinkageCondition() {
      listLinkageCondition({
        linkageId: this.linkage.linkageId
      }).then(res => {
        const { code, data } = res
        const conditionList = []
        if (code === '200') {
          for (const condition of data) {
            conditionList.push(this.formatCondition(condition))
          }
        }
        this.conditionList = conditionList
      })
    }
  }
}
</script>

